import React, { useState, useEffect } from 'react'

const TypewriterText = ({ text, speed = 100, className = '', onComplete = null, delay = 0 }) => {
  const [displayText, setDisplayText] = useState('')
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isComplete, setIsComplete] = useState(false)
  const [hasStarted, setHasStarted] = useState(delay === 0)

  // 处理延迟开始
  useEffect(() => {
    if (delay > 0 && !hasStarted) {
      const delayTimer = setTimeout(() => {
        setHasStarted(true)
      }, delay)
      return () => clearTimeout(delayTimer)
    }
  }, [delay, hasStarted])

  useEffect(() => {
    if (hasStarted && currentIndex < text.length) {
      const timer = setTimeout(() => {
        setDisplayText(prev => prev + text[currentIndex])
        setCurrentIndex(prev => prev + 1)
      }, speed)

      return () => clearTimeout(timer)
    } else if (hasStarted && !isComplete) {
      setIsComplete(true)
      if (onComplete) {
        onComplete()
      }
    }
  }, [currentIndex, text, speed, isComplete, onComplete, hasStarted])

  // 重置动画当文本改变时
  useEffect(() => {
    setDisplayText('')
    setCurrentIndex(0)
    setIsComplete(false)
    setHasStarted(delay === 0)
  }, [text, delay])

  return (
    <span className={className}>
      {displayText}
      {hasStarted && !isComplete && (
        <span className="animate-pulse text-gold-500">|</span>
      )}
    </span>
  )
}

export default TypewriterText
